﻿#include "EditorMeshPageView.h"
#include "EditorMeshPageViewModel.h"
#include "Widgets/ViewportWidget.h"
#include "Widgets/Mouse/MouseWidget.h"
#include "Widgets/TextWidget.h"

void REditorMeshPageView::BindViewModel(TSharedObjectPtr<REditorPageViewModel> InViewModel)
{
    //Super::BindViewModel(InViewModel);
    ViewModel = InViewModel;
}

void REditorMeshPageView::CreateWidget(TSharedObjectPtr<RWidget> InParent)
{
    //create a  viewport widget
    auto PreviewViewport=NewWidget<RViewportWidget>(InParent);
    PreviewViewport->SetScene(ViewModel->GetMeshScene());
    PreviewViewport->Anchor.Fill(InParent);
    PreviewViewport->bForceUseDefaultParameters=true;
    RViewportWidgetWeakPtr PreviewViewportWeak=PreviewViewport;

    SQuat Rotation=SQuat::FromEuler(
        SVec3(CMathBase::DegreeToRadian(-45.f),0,0));
    PreviewViewport->ViewportRotation=Rotation;
    PreviewViewport->ViewportPosition=
         Rotation.GetForwardDirection()*-ViewModel->GetViewDistanceToMesh()
            +SVec3(0,0,ViewModel->GetMeshHeight()*0.5f);

    //create a widget to let user to rotate view
    auto Mouse =NewWidget<RMouseWidget>(InParent);
    Mouse->Anchor.Fill(InParent);

    Mouse->Drag->bIsEnabled=true;

    //you cant drag the mouse on two widgets at the same time
    //so use a static variable is safe
    static SVec2 InitMousePos; 
    static SQuat InitRotationQuat;
    Mouse->Drag->OnDragStarted.Bind([PreviewViewportWeak,this]()
    {
        InitMousePos=PreviewViewportWeak->GetMousePositionInWidget();
        InitRotationQuat=PreviewViewportWeak->ViewportRotation.Get();
    });

    Mouse->Drag->OnDragMoved.Bind([this,PreviewViewportWeak](const SVec2&)
    {
        auto MouseDelta=PreviewViewportWeak->GetMousePositionInWidget()
            -InitMousePos;

        //camera coordinate Y
        float Pitch= -MouseDelta.Y*0.01f;
            Pitch=CMath::Clamp(Pitch, -CMathBase::HalfPi,CMathBase::HalfPi);
        
        //scene coordinate Z;
        float Yaw=-MouseDelta.X*0.01f; 

        SQuat FinalRotation= SQuat::FromEuler(SVec3(0,0,Yaw))*InitRotationQuat*SQuat::FromEuler(SVec3(Pitch,0,0)) ;

        PreviewViewportWeak->ViewportRotation=FinalRotation;

        PreviewViewportWeak->ViewportPosition=
            FinalRotation.GetForwardDirection()*-ViewModel->GetViewDistanceToMesh()
            +SVec3(0,0,ViewModel->GetMeshHeight()*0.5f);
    });

}
